package top.younote.cherry.selenium.impl;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.younote.cherry.model.bo.WorldCupBO;
import top.younote.cherry.selenium.BaiduService;
import top.younote.cherry.service.IMailService;

import java.io.File;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description:
 * @Author: duanluyao
 * @CreateTime: 2021/10/14 11:03:26
 */
@Slf4j
@Service
public class BaiduServiceImpl implements BaiduService {
    @Autowired
    private IMailService iMailService;

    @Override
    public File saveCalender() {
        try {
            ChromeOptions chromeOptions = new ChromeOptions();
//            chromeOptions.setHeadless(true);
            WebDriver driver = new ChromeDriver(chromeOptions);
//            RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), chromeOptions);
            driver.get("http://www.baidu.com/s?ie=UTF-8&wd=日历");
            WebElement location = driver.findElement(By.className("calendar_1ARDi"));
            File screenshotAs = location.getScreenshotAs(OutputType.FILE);
            driver.quit();
            return screenshotAs;
        } catch (Exception e) {
            iMailService.sendLogs(JSON.toJSONString(e));
            log.error(e.getMessage(), e);
            return null;
        }
    }

    @Override
    public File saveWeather() {
        try {
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.setHeadless(true);
            WebDriver driver = new ChromeDriver(chromeOptions);
//            RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), chromeOptions);
            driver.get("http://www.baidu.com/s?ie=UTF-8&wd=上海天气");
            WebElement location = driver.findElement(new By.ByClassName("op_weather4_twoicon"));
            File screenshotAs = location.getScreenshotAs(OutputType.FILE);
            driver.quit();
            return screenshotAs;
        } catch (Exception e) {
            iMailService.sendLogs("抓取天气失败！");
            log.error(e.getMessage(), e);
            return null;
        }
    }

    @Override
    public Map<String, String> getBaiduRealtime() {
        try {
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.setHeadless(true);
            WebDriver driver = new ChromeDriver(chromeOptions);
//            RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), chromeOptions);
            driver.manage().window().setSize(new Dimension(1080, 1024));
            driver.get("https://top.baidu.com/board?tab=realtime");
            String pageSource = driver.getPageSource();
            driver.quit();
            Document document = Jsoup.parse(pageSource);
            Map<String, String> listNews = new LinkedHashMap<>();
            AtomicInteger num = new AtomicInteger(1);
            document.getElementsByClass("content_1YWBm").forEach(res -> {
                String title = res.getElementsByClass("c-single-text-ellipsis").text();
                Element message = res.getElementsByClass("hot-desc_1m_jR").first();
                String text = message.getAllElements().first().text().replace("查看更多>", "");
                title = "<i>No." + num.getAndIncrement() + "&nbsp;</i>" + title;
                listNews.put(title, text);
            });
            return listNews;
        } catch (Exception e) {
            iMailService.sendLogs("抓取百度热搜失败！");
            log.error("抓取百度热搜失败！", e);
            return null;
        }
    }

    @Override
    public Map<String, String> getBaiduRealtimeV2() {
        try {
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.setHeadless(true);
//            WebDriver driver = new ChromeDriver(chromeOptions);
            RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), chromeOptions);
            driver.manage().window().setSize(new Dimension(4096, 2160));
            driver.get("https://top.baidu.com/board?tab=realtime");
            List<WebElement> elements = driver.findElements(By.className("category-wrap_iQLoo"));
            Map<String, File> maps = new LinkedHashMap<>();
            AtomicInteger cnt = new AtomicInteger(0);
            StringBuilder content = new StringBuilder();
            elements.forEach(res -> {
                File screenshotAs = res.getScreenshotAs(OutputType.FILE);
                int andIncrement = cnt.getAndIncrement();
                content.append(String.format("<img src=\'cid:%s\'/>", andIncrement));
                maps.put(String.valueOf(andIncrement), screenshotAs);
            });
            iMailService.sendInlineResourceMail("duanyu@martind.cn", "新闻", content.toString(),
                    maps);
            driver.quit();
            return null;
        } catch (Exception e) {
            iMailService.sendLogs("抓取百度热搜失败！");
            log.error("抓取百度热搜失败！", e);
            return null;
        }
    }

    @Override
    public void getBaiduHotSearch() {

    }

    @SneakyThrows
    @Override
    public WorldCupBO getWorldCup() {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Accept", "application/json, text/plain, */*");
        httpHeaders.set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
        httpHeaders.set("Connection", "keep-alive");
        httpHeaders.set("Host", "gw.m.163.com");
        httpHeaders.set("Origin", "http://sports.163.com");
        httpHeaders.set("Referer", "http://sports.163.com");
        httpHeaders.set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36");
        HttpEntity<String> httpEntity = new HttpEntity(httpHeaders);
        ResponseEntity<String> response = restTemplate.exchange("http://gw.m.163.com/base/worldCup/qatar/schedule", HttpMethod.GET, httpEntity, String.class);
        return JSON.parseObject(JSON.parseObject(response.getBody()).get("data").toString(), WorldCupBO.class);
    }

    //*[@id="sanRoot"]/main/div[2]/div
    public static void main(String[] args) {
        try {
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.setHeadless(true);
//            WebDriver driver = new ChromeDriver(chromeOptions);
            RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), chromeOptions);
            driver.manage().window().setSize(new Dimension(4096, 2160));
            driver.manage().window().fullscreen();
            driver.get("https://top.baidu.com/board?tab=homepage");
//            Thread.sleep(10000);
            File screenshotAs1 = driver.findElement(new By.ByClassName("content-wrap_1E_gm")).getScreenshotAs(OutputType.FILE);
            File screenshotAs = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(screenshotAs, new File("./t.png"));
            FileUtils.copyFile(screenshotAs1, new File("./t1.png"));
            String pageSource = driver.getPageSource();
            driver.quit();
            Document document = Jsoup.parse(pageSource);
            System.out.println(document);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
